package spark.network.strategy;

import spark.network.ClockSynchronizer;
import spark.network.protocol.*;
import spark.utility.OutWrapper;

import java.util.Collection;

public class ClockSyncResStrategy implements IProtocolHandleStrategy<ClockSyncRes> {
	private ClockSynchronizer clockSynchronizer;
	private int clockSyncRequestsToReceive;

	public ClockSyncResStrategy(ClockSynchronizer clockSynchronizer, int clockSyncRequestsToSend) {
		this.clockSynchronizer = clockSynchronizer;
		this.clockSyncRequestsToReceive = clockSyncRequestsToSend;
	}

	@Override
	public void handle(ClockSyncRes packet, OutWrapper<Response> acknowledgement, Collection<Base> responses) {
		clockSynchronizer.updateSyncData(packet.getSession(), packet.getRequest().getRequestNumber(), packet.getTimeStampReceive(), packet.getLocalTime());
		if(clockSynchronizer.getCompleteSyncDataCount(packet.getSession()) == clockSyncRequestsToReceive) {
			ClockSynchronizer.SyncData shortestSyncData = clockSynchronizer.getShortestSyncData(packet.getSession());
			clockSynchronizer.clearSyncData(packet.getSession());
			long clientAdjustment = shortestSyncData.serverReceiveTime - shortestSyncData.getAdjustedClientLocalTime();
			ClockAdjustNotice clockAdjustNotice = new ClockAdjustNotice();
			clockAdjustNotice.setAdjustment(clientAdjustment);
			responses.add(clockAdjustNotice);
		}
	}
}